#!/usr/bin/python26 -u
# Alf & pt UWS quicky hacky python to fireup nectar vm using EC2 API and install RStudio
# Uber Dojo 20120925 demo piece - warning here lies all sorts of bad!

import boto
import os
import time
import sys
import subprocess as sub
import ConfigParser

from boto.ec2.connection import EC2Connection
from boto.ec2.regioninfo import *

def doCmd(cmd):
  print '<i>' + cmd + '</i>'
  p = sub.Popen(cmd, shell=True, stdout=sub.PIPE).stdout

  while 1:
    line = p.readline().rstrip('\n')
    print 'out:' + line
    if not line:
      break

config = ConfigParser.RawConfigParser()
config.read('rstudio.cfg')

print "Content-type: text/html"
print ""
print "<html><head><title>RStudio on NeCTAR</title></head>"
print "<body bgcolor=#ffffff>"
# print "<h1>Creating R Studio Server NeCTAR Cloud Instance</h1>"
print "<pre>"

EC2_ACCESS_KEY = config.get("EC2","access_key")
EC2_SECRET_KEY = config.get("EC2","secret_key")
regionName = config.get("EC2","region_name")
regionEndpoint = config.get("EC2","region_endpoint")
pem = config.get("EC2", "pem")
pem_path = config.get("EC2", "pem_path")
install_sh = config.get("EC2", "install_sh")
dest_sh = config.get("EC2", "dest_sh")
source_zip = config.get("EC2", "source_zip")
dest_zip = config.get("EC2", "dest_zip")

#print 'EC2_ACCESS_KEY=' + EC2_ACCESS_KEY
#print 'EC2_SECRET_KEY=' + EC2_SECRET_KEY
print 'regionName=' + regionName
print 'regionEndpoint=' + regionEndpoint
#print 'pem=' + pem
#print 'pem_path=' + pem_path
print 'install_sh=' + install_sh
print 'dest_sh=' + dest_sh
print 'source_zip=' + source_zip
print 'dest_zip=' + dest_zip

region = RegionInfo(name=regionName, endpoint=regionEndpoint)

connection = boto.connect_ec2(aws_access_key_id=EC2_ACCESS_KEY,
                    aws_secret_access_key=EC2_SECRET_KEY,
                    is_secure=False,
                    region=region,
                    port=8773,
                    path="/services/Cloud")

reservations = connection.get_all_instances()

print ""
print "<b>Reservations:</b>",
print reservations

# ami-0000000d is CentOS 6.2
ir = connection.run_instances('ami-0000000d',key_name=pem,security_groups=['SSH','ICMP','webserver'])

print ""
print "<b>Instance reservation:</b>",
print ir

i = ir.instances[0]

ip = ""
print ""
print "<b>Instance Pending:</b> ",
while ip == "":
	i.update()
	print '.',
	time.sleep(5)
	
ip = i.ip_address

print ""
print ""
print "Have IP address " + ip

print '<h3>Try this in a few minutes - <a href="http://%s/">http://%s/</a></h3>' % (ip, ip)

wait = 45
print "<b>Waiting for VM boot and ssh to start (about %s seconds)...</b>" % wait
time.sleep( wait )

# was causing problems with new keys
# known_hosts = "~/.ssh/known_hosts"
# if os.path.isfile(known_hosts):
#  os.remove( known_hosts )

print ""
print "<b>Pushing RStudio setup script onto VM %s...</b>" % ip
cmd = "scp -i %s -o ConnectTimeout=300 -o StrictHostKeyChecking=no %s root@%s:%s 2>&1" % (pem_path, install_sh, ip, dest_sh)
doCmd(cmd)

print ""
print "<b>Copy researcher R bundle to VM...</b>"
cmd = "scp -i %s -o StrictHostKeyChecking=no %s root@%s:%s 2>&1" % (pem_path, source_zip, ip, dest_zip)
doCmd(cmd)

print ""
print "<b>Execute remote RStudio setup script...</b>"
cmd = "ssh -i %s -o ConnectTimeout=300 -o StrictHostKeyChecking=no root@%s sh %s 2>&1" % (pem_path, ip, dest_sh)
doCmd(cmd)

print "</pre>"
print ""
print '<h1><a href="http://%s/">http://%s/</a></h1>' % (ip, ip)

print "</body>"
print "</html>"
